import 'package:flutter/material.dart';
import 'package:netflix_social/models/video.dart';

class VideoProvider with ChangeNotifier {
  List<Video> _videos = [];
  List<Video> _favorites = [];
  List<Video> _continueWatching = [];
  List<Video> _trending = [];
  List<Video> _recommended = [];
  List<Video> _downloadedVideos = []; // 已下载的视频列表
  List<Map<String, dynamic>> _downloadingVideos = []; // 正在下载的视频列表
  bool _isLoading = false;
  bool _isSearching = false; 
  List<Video> _searchResults = []; 
  Video? _currentVideo; // 添加当前视频属性

  List<Video> get videos => _videos;
  List<Video> get favorites => _favorites;
  List<Video> get continueWatching => _continueWatching;
  List<Video> get trending => _trending;
  List<Video> get recommended => _recommended;
  List<Video> get downloadedVideos => _downloadedVideos; // 添加已下载视频的getter
  List<Map<String, dynamic>> get downloadingVideos => _downloadingVideos; // 添加正在下载视频的getter
  bool get isLoading => _isLoading;
  bool get isSearching => _isSearching; 
  List<Video> get searchResults => _searchResults; 
  Video? get currentVideo => _currentVideo; // 添加currentVideo的getter

  // 初始化数据
  Future<void> initialize() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会从API获取这些数据
      // 这里我们使用模拟数据
      await Future.delayed(const Duration(milliseconds: 800));
      _loadMockData();
    } catch (e) {
      print('初始化视频数据时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取视频详情
  Future<Video?> getVideoDetails(String videoId) async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会从API获取特定视频的详细信息
      // 这里我们只是从现有列表中查找
      await Future.delayed(const Duration(milliseconds: 500));
      final video = _videos.firstWhere((video) => video.id == videoId);
      _currentVideo = video; // 设置当前视频
      return video;
    } catch (e) {
      print('获取视频详情时出错: $e');
      return null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 搜索视频
  Future<List<Video>> searchVideos(String query) async {
    _isLoading = true;
    _isSearching = true; // 设置搜索状态为true
    _searchResults = []; // 清空之前的搜索结果
    notifyListeners();

    try {
      // 在实际应用中，您会发送搜索请求到API
      // 这里我们只是过滤现有列表
      await Future.delayed(const Duration(milliseconds: 300));
      final lowercaseQuery = query.toLowerCase();
      final results = _videos.where((video) {
        return video.title.toLowerCase().contains(lowercaseQuery) ||
            video.description.toLowerCase().contains(lowercaseQuery) ||
            video.category.toLowerCase().contains(lowercaseQuery) ||
            video.tags.any((tag) => tag.toLowerCase().contains(lowercaseQuery));
      }).toList();
      
      // 保存搜索结果
      _searchResults = results;
      return results;
    } catch (e) {
      print('搜索视频时出错: $e');
      return [];
    } finally {
      _isLoading = false;
      _isSearching = false; // 搜索完成
      notifyListeners();
    }
  }

  // 切换收藏状态
  Future<bool> toggleFavorite(String videoId) async {
    try {
      final videoIndex = _videos.indexWhere((video) => video.id == videoId);
      if (videoIndex == -1) return false;

      // 在实际应用中，您会发送请求到API来更新收藏状态
      final updatedVideo = _videos[videoIndex].copyWith(
        isFavorite: !_videos[videoIndex].isFavorite,
      );
      _videos[videoIndex] = updatedVideo;

      // 更新收藏列表
      if (updatedVideo.isFavorite) {
        _favorites.add(updatedVideo);
      } else {
        _favorites.removeWhere((video) => video.id == videoId);
      }

      notifyListeners();
      return true;
    } catch (e) {
      print('切换收藏状态时出错: $e');
      return false;
    }
  }

  // 更新观看进度
  Future<bool> updateWatchProgress(String videoId, int progress) async {
    try {
      final videoIndex = _videos.indexWhere((video) => video.id == videoId);
      if (videoIndex == -1) return false;

      // 在实际应用中，您会发送请求到API来更新观看进度
      final updatedVideo = _videos[videoIndex].copyWith(
        watchProgress: progress,
      );
      _videos[videoIndex] = updatedVideo;

      // 如果进度大于0但小于100，添加到继续观看列表
      if (progress > 0 && progress < 100) {
        final continueIndex = _continueWatching.indexWhere((video) => video.id == videoId);
        if (continueIndex == -1) {
          _continueWatching.add(updatedVideo);
        } else {
          _continueWatching[continueIndex] = updatedVideo;
        }
      } else if (progress >= 100) {
        // 如果已完成观看，从继续观看列表中移除
        _continueWatching.removeWhere((video) => video.id == videoId);
      }

      notifyListeners();
      return true;
    } catch (e) {
      print('更新观看进度时出错: $e');
      return false;
    }
  }

  // 获取特定类别的视频
  List<Video> getVideosByCategory(String category) {
    return _videos.where((video) => video.category == category).toList();
  }

  // 添加到观看历史
  Future<bool> addToHistory(String videoId) async {
    try {
      final videoIndex = _videos.indexWhere((video) => video.id == videoId);
      if (videoIndex == -1) return false;

      final video = _videos[videoIndex];
      
      // 在实际应用中，您会发送请求到API来记录观看历史
      
      // 如果视频不在继续观看列表中，添加它
      final continueIndex = _continueWatching.indexWhere((v) => v.id == videoId);
      if (continueIndex == -1) {
        // 设置初始进度为1%
        final updatedVideo = video.copyWith(
          watchProgress: video.watchProgress > 0 ? video.watchProgress : 1,
        );
        _continueWatching.add(updatedVideo);
        
        // 同时更新主列表中的视频
        _videos[videoIndex] = updatedVideo;
      }
      
      // 重排序继续观看列表，将最近观看的放在最前面
      if (continueIndex > 0) {
        final videoToMove = _continueWatching.removeAt(continueIndex);
        _continueWatching.insert(0, videoToMove);
      }

      notifyListeners();
      return true;
    } catch (e) {
      print('添加到观看历史时出错: $e');
      return false;
    }
  }

  // 添加视频下载功能
  Future<bool> downloadVideo(String videoId) async {
    _isLoading = true;
    notifyListeners();
    
    try {
      // 查找视频
      final videoIndex = _videos.indexWhere((video) => video.id == videoId);
      if (videoIndex == -1) return false;
      
      final video = _videos[videoIndex];
      
      // 检查是否已经下载了这个视频
      if (_downloadedVideos.any((v) => v.id == videoId)) {
        return true; // 已经下载过了
      }
      
      // 检查是否已经在下载中
      if (_downloadingVideos.any((item) => item['video'].id == videoId)) {
        return true; // 已经在下载队列中
      }
      
      // 添加到下载队列
      _downloadingVideos.add({
        'video': video,
        'progress': 0.0,
        'startTime': DateTime.now(),
      });
      
      notifyListeners();
      
      // 模拟下载过程 - 实际应用中会使用真正的下载逻辑
      for (int i = 1; i <= 10; i++) {
        await Future.delayed(const Duration(milliseconds: 300));
        
        // 更新下载进度
        final index = _downloadingVideos.indexWhere((item) => item['video'].id == videoId);
        if (index != -1) {
          _downloadingVideos[index]['progress'] = i / 10;
          notifyListeners();
        }
      }
      
      // 在实际应用中，这里会将视频下载到本地存储
      // 并更新视频的offlineUrl属性指向本地文件
      final updatedVideo = video.copyWith(
        offlineUrl: 'file:///local/videos/${video.id}.mp4',
        // 模拟一个文件大小
        fileSize: video.fileSize ?? (50 + (video.id.hashCode % 100)) * 1024 * 1024,
      );
      
      // 更新视频列表
      _videos[videoIndex] = updatedVideo;
      
      // 如果这是当前视频，也更新当前视频
      if (_currentVideo?.id == videoId) {
        _currentVideo = updatedVideo;
      }
      
      // 从下载队列中移除
      _downloadingVideos.removeWhere((item) => item['video'].id == videoId);
      
      // 添加到已下载视频列表
      _downloadedVideos.add(updatedVideo);
      
      notifyListeners();
      return true;
    } catch (e) {
      print('下载视频时出错: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
  
  // 获取类似视频推荐
  List<Video> getSimilarVideos(String videoId) {
    if (videoId.isEmpty) return [];
    
    try {
      // 找到当前视频
      final currentVideo = _videos.firstWhere(
        (video) => video.id == videoId,
        orElse: () => _videos.first,
      );
      
      // 基于类别和标签查找类似视频
      return _videos.where((video) {
        // 排除当前视频
        if (video.id == videoId) return false;
        
        // 同类别加分
        if (video.category == currentVideo.category) return true;
        
        // 有共同标签加分
        final commonTags = video.tags.where(
          (tag) => currentVideo.tags.contains(tag)
        ).length;
        
        return commonTags > 0;
      }).take(8).toList(); // 最多返回8个推荐
    } catch (e) {
      print('获取类似视频时出错: $e');
      return [];
    }
  }

  // 加载模拟数据
  void _loadMockData() {
    // 模拟一些视频数据
    _videos = [
      Video(
        id: '1',
        title: '流浪地球2',
        description: '太阳即将毁灭，人类在地球表面建造出巨大的推进器，寻找新家园。然而宇宙之路危机四伏，为了拯救地球，流浪地球时代的年轻人再次挺身而出，展开争分夺秒的生命之战。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1626814026160-2237a95fc5a0',
        videoUrl: 'https://example.com/videos/wandering-earth-2.mp4',
        category: '科幻',
        year: 2023,
        duration: '173分钟',
        rating: 9.8,
        tags: ['科幻', '冒险', '中国电影'],
        cast: ['吴京', '刘德华', '李光洁'],
        director: '郭帆',
        isOriginal: true,
        releaseDate: DateTime(2023, 1, 22),
        viewCount: 1200000,
        likeCount: 98000,
        commentCount: 12500,
        isFavorite: true,
        watchProgress: 45,
      ),
      Video(
        id: '2',
        title: '三体',
        description: '改编自刘慈欣的同名小说，讲述在文化大革命期间，一次秘密军事项目向宇宙发出信号，引来了三体文明的注意。地球文明和三体文明由此展开一场跨越星系的文明间博弈。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1536440136628-849c177e76a1',
        videoUrl: 'https://example.com/videos/three-body.mp4',
        category: '科幻',
        year: 2023,
        duration: '45分钟/集',
        rating: 9.2,
        tags: ['科幻', '悬疑', '改编'],
        cast: ['张鲁一', '于和伟', '王子文'],
        director: '杨磊',
        isOriginal: false,
        releaseDate: DateTime(2023, 1, 15),
        viewCount: 820000,
        likeCount: 76000,
        commentCount: 9800,
        isFavorite: false,
        watchProgress: 70,
      ),
      Video(
        id: '3',
        title: '满江红',
        description: '南宋绍兴年间，岳飞死后四年，秦桧率领的朝廷腐败透顶。一个上将之死牵出大案，一群侠客要查出真相，一场危机正在爆发。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1533613220915-609f661a6fe1',
        videoUrl: 'https://example.com/videos/full-river-red.mp4',
        category: '剧情',
        year: 2023,
        duration: '159分钟',
        rating: 8.7,
        tags: ['剧情', '悬疑', '喜剧'],
        cast: ['沈腾', '易烊千玺', '张译'],
        director: '张艺谋',
        isOriginal: false,
        releaseDate: DateTime(2023, 1, 22),
        viewCount: 950000,
        likeCount: 85000,
        commentCount: 10200,
        isFavorite: true,
        watchProgress: 85,
      ),
      Video(
        id: '4',
        title: '红海行动',
        description: '中国海军"蛟龙突击队"在非洲海域执行反海盗任务，突然发现了恐怖组织的重大行动计划，海军战士们临危受命，前往非洲解救中国人质。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1594908900066-3f47337549d8',
        videoUrl: 'https://example.com/videos/operation-red-sea.mp4',
        category: '动作',
        year: 2018,
        duration: '142分钟',
        rating: 8.5,
        tags: ['动作', '战争', '真实事件改编'],
        cast: ['张译', '黄景瑜', '海清'],
        director: '林超贤',
        isOriginal: false,
        releaseDate: DateTime(2018, 2, 16),
        viewCount: 1050000,
        likeCount: 92000,
        commentCount: 11300,
        isFavorite: false,
        watchProgress: 0,
      ),
      Video(
        id: '5',
        title: '长津湖',
        description: '1950年，中国人民志愿军赴朝作战，在极寒条件下，东线作战部队凭着钢铁意志和英勇无畏的战斗精神一路推进，打出了军威国威。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1611523658822-385aa008324c',
        videoUrl: 'https://example.com/videos/battle-at-lake-changjin.mp4',
        category: '战争',
        year: 2021,
        duration: '176分钟',
        rating: 9.0,
        tags: ['战争', '历史', '抗美援朝'],
        cast: ['吴京', '易烊千玺', '朱亚文'],
        director: '陈凯歌',
        isOriginal: false,
        releaseDate: DateTime(2021, 9, 30),
        viewCount: 1150000,
        likeCount: 95000,
        commentCount: 12200,
        isFavorite: false,
        watchProgress: 0,
      ),
      Video(
        id: '6',
        title: '独行月球',
        description: '人类为抵御小行星的撞击，拯救地球，在月球部署了推动计划。陨石提前来袭，全员紧急撤离时，维修工独孤月被错误的留在了月球。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1535016120720-40c646be5580',
        videoUrl: 'https://example.com/videos/moon-man.mp4',
        category: '喜剧',
        year: 2022,
        duration: '130分钟',
        rating: 8.3,
        tags: ['喜剧', '科幻', '冒险'],
        cast: ['沈腾', '马丽', '常远'],
        director: '张吃鱼',
        isOriginal: false,
        releaseDate: DateTime(2022, 7, 29),
        viewCount: 980000,
        likeCount: 88000,
        commentCount: 10800,
        isFavorite: false,
        watchProgress: 30,
      ),
      Video(
        id: '7',
        title: '战狼2',
        description: '退役特种兵冷锋在非洲经商被卷入一场政变，突然被提前来袭，全员紧急撤离时，维修工独孤月被错误的留在了月球。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1611162618071-b39a2ec055fb',
        videoUrl: 'https://example.com/videos/wolf-warrior-2.mp4',
        category: '动作',
        year: 2017,
        duration: '123分钟',
        rating: 8.7,
        tags: ['动作', '战争', '爱国'],
        cast: ['吴京', '卢靖姗', '张翰'],
        director: '吴京',
        isOriginal: false,
        releaseDate: DateTime(2017, 7, 27),
        viewCount: 1250000,
        likeCount: 105000,
        commentCount: 14500,
        isFavorite: true,
        watchProgress: 100,
      ),
      Video(
        id: '8',
        title: '你好，李焕英',
        description: '失意少女贾晓玲穿越回到1981年，成为了自己20岁的母亲李焕英身边的"闺蜜"，经历一系列奇妙旅程后，她逐渐理解了母亲对自己的深厚感情。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1635805737707-575885ab0820',
        videoUrl: 'https://example.com/videos/hi-mom.mp4',
        category: '喜剧',
        year: 2021,
        duration: '128分钟',
        rating: 8.5,
        tags: ['喜剧', '家庭', '穿越'],
        cast: ['贾玲', '张小斐', '沈腾'],
        director: '贾玲',
        isOriginal: false,
        releaseDate: DateTime(2021, 2, 12),
        viewCount: 1120000,
        likeCount: 96000,
        commentCount: 12100,
        isFavorite: false,
        watchProgress: 0,
      ),
      Video(
        id: '9',
        title: '他是谁',
        description: '讲述了一个发生在上世纪90年代的悬疑故事，刑警卫国平在追查一宗奇怪的杀人案时，发现了一个惊天的秘密。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1618172193622-ae2d025f4032',
        videoUrl: 'https://example.com/videos/who-is-he.mp4',
        category: '悬疑',
        year: 2022,
        duration: '132分钟',
        rating: 8.2,
        tags: ['悬疑', '犯罪', '剧情'],
        cast: ['梁朝伟', '段奕宏', '张震'],
        director: '姜文',
        isOriginal: false,
        releaseDate: DateTime(2022, 10, 1),
        viewCount: 890000,
        likeCount: 79000,
        commentCount: 9500,
        isFavorite: false,
        watchProgress: 0,
      ),
      Video(
        id: '10',
        title: '神探大战',
        description: '被称为"神探"的警方前线精英李俊因破案方法独特，屡破奇案。然而，他却因一宗案件，陷入困境，在迷雾中，寻找真相。',
        thumbnailUrl: 'https://images.unsplash.com/photo-1509347528160-9a9e33742cdb',
        videoUrl: 'https://example.com/videos/detective-vs-sleuths.mp4',
        category: '悬疑',
        year: 2022,
        duration: '101分钟',
        rating: 7.5,
        tags: ['悬疑', '犯罪', '动作'],
        cast: ['刘青云', '蔡卓妍', '林峯'],
        director: '韦家辉',
        isOriginal: false,
        releaseDate: DateTime(2022, 7, 8),
        viewCount: 780000,
        likeCount: 68000,
        commentCount: 8200,
        isFavorite: false,
        watchProgress: 0,
      ),
    ];

    // 分类整理数据
    _favorites = _videos.where((video) => video.isFavorite).toList();
    _continueWatching = _videos.where((video) => video.watchProgress > 0 && video.watchProgress < 100).toList();
    _trending = List.from(_videos)..sort((a, b) => b.viewCount.compareTo(a.viewCount));
    _recommended = List.from(_videos)..sort((a, b) => b.rating.compareTo(a.rating));
    
    // 模拟一些已下载的视频
    _downloadedVideos = [
      _videos[0],
      _videos[2],
      _videos[6],
    ];
  }
}
